package com.itheima.aop;

import com.alibaba.fastjson.JSONObject;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @version 1.0
 * @Author 郭腾高
 * @Date 2024/9/8 22:57
 */
@Component
@Aspect
public class LogAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OperateLogMapper operateLogMapper;
   @Around("@annotation(com.itheima.anno.Log)")
    public Object recordLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
       //操作人id
       //解析jwt令牌获得id
       String jwt = request.getHeader("token");
       Claims claims = JwtUtils.parseJWT(jwt);
       Integer operateUser = (Integer) claims.get("id");
       //操作时间
       LocalDateTime operateTime = LocalDateTime.now();
       //操作类名
       String className = proceedingJoinPoint.getTarget().getClass().getName();
       //操作方法名
       String methordName = proceedingJoinPoint.getSignature().getName();
       //操作方法参数
       Object[] args = proceedingJoinPoint.getArgs();
       String methordParams = Arrays.toString(args);


       long begin = System.currentTimeMillis();
       //调用原始目标返回值
       Object result = proceedingJoinPoint.proceed();
       long end = System.currentTimeMillis();
       //方法返回值
       String returnValue = JSONObject.toJSONString(result);
       //操作耗时
       Long costTime = end - begin;


       //记录操作日志
       OperateLog operateLog = new OperateLog(null,operateUser,operateTime,className,methordName,methordParams,returnValue,costTime);
       operateLogMapper.insert(operateLog);

       return result;
   }
}
